package com.cell.service.user.impl.location;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cell.dao.location.ProvinceDao;
import com.cell.dao.user.location.LocationDetailDao;
import com.cell.pojo.DTO.user.location.UserUpdateLocationDTO;
import com.cell.pojo.VO.user.UserLocationDetailVO;
import com.cell.pojo.entity.location.Province;
import com.cell.pojo.entity.user.location.LocationDetail;
import com.cell.pojo.entity.user.location.UserLocation;
import com.cell.dao.user.location.UserLocationDao;
import com.cell.service.user.location.IUserLocationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cloudJiang
 * @since 2022-06-04
 */
@Service
public class UserLocationServiceImpl extends ServiceImpl<UserLocationDao, UserLocation> implements IUserLocationService {

    @Autowired
    UserLocationDao locationDao;
    @Autowired
    LocationDetailDao locationDetailDao;
    @Autowired
    ProvinceDao provinceDao;

    @Override
    public void updateLocation(UserUpdateLocationDTO userUpdateLocationDTO) {
        //分别获取位置表和位置细节表
        UserLocation userLocation = locationDao.selectById(userUpdateLocationDTO.getLocationId());
        LocationDetail locationDetail = locationDetailDao.selectById(userLocation.getDetailId());

        //获取更新后的省份id
        LambdaQueryWrapper<Province> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Province::getName, userUpdateLocationDTO.getProvince());
        Integer provinceId = provinceDao.selectOne(wrapper).getId();

        //更新信息
        userLocation.setCityName(userUpdateLocationDTO.getCity());
        userLocation.setProvinceId(provinceId);
        locationDetail.setLocationDetails(userUpdateLocationDTO.getDetail());
        locationDetail.setDistrict(userUpdateLocationDTO.getDistrict());
        locationDetail.setCommunity(userUpdateLocationDTO.getCommunity());
        //传入数据库
        locationDao.updateById(userLocation);
        locationDetailDao.updateById(locationDetail);
    }

    @Override
    public UserLocationDetailVO getLocation(Long locationId) {
        //获取位置表和位置细节表
        UserLocation userLocation = locationDao.selectById(locationId);
        LocationDetail locationDetail = locationDetailDao.selectById(userLocation.getDetailId());
        UserLocationDetailVO vo = new UserLocationDetailVO();

        vo.setCommunity(locationDetail.getCommunity());
        vo.setDistrict(locationDetail.getDistrict());
        vo.setDetail(locationDetail.getLocationDetails());
        vo.setCity(userLocation.getCityName());
        String provinceName = provinceDao.selectById(userLocation.getProvinceId()).getName();
        vo.setProvince(provinceName);

        return vo;
    }
}
